#pragma once

#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<cstring>
#include<cerrno>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<functional>
#include<unordered_map>

using func_t = std::function<std::string(const std::string&)>;

std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;
static int defaultNum = 4096;

enum    
{
    SocketErr = 1,
    BindErr,
};

class UdpServer
{
public:
    UdpServer(const uint16_t& port = defaultport ,const std::string& ip = defaultip)
        :_sockfd(0)
        ,_ip(ip)
        ,_port(port)
        ,_isrunning(false)
    {}

    void init()
    {
        //1.创建套接字
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)
        {
            std::cerr << "socket create failed ,errno: "<< errno << " ,err string " << strerror(errno) << std::endl;
            exit(SocketErr);
        }
        std::cout << "socket create success" << std::endl;

        //2.bind绑定
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);//本主机转网络
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());  //1.字符串转成整型  2.主机转网络
        local.sin_addr.s_addr = htonl(INADDR_ANY);

        socklen_t len = sizeof(local);
        int n = bind(_sockfd,(const struct sockaddr*)&local,len);
        if(n < 0 )
        {
            std::cerr << "bind failed ,errno: "<< errno << " ,err string " << strerror(errno) << std::endl;
            exit(BindErr);
        }
        std::cout << "bind success" << std::endl;
    }

    void CheckUser(const struct sockaddr_in& client,std::string& clientip,uint16_t clientport)
    {
        auto it = _online_user.find(clientip);
        if(it == _online_user.end())
        {
            _online_user.insert(make_pair(clientip,client));
            std::cout << "[" << clientip << ":" << clientport << "]" << " add online_user";
        }
    }

    void BroadCast(const std::string& info,const std::string& clientip,uint16_t clientport)
    {
        for(auto& e: _online_user)
        {
            std::string result = "[";
            result += clientip;
            result += ":";
            result += "clientport";
            result += "]# ";
            result += info;
            socklen_t len = sizeof(e.second);
            sendto(_sockfd,result.c_str(),result.size(),0,(const sockaddr*)&e.second,len);
        }
    }

    void run()
    {
        _isrunning = true;
        char inbuff[defaultNum];
        while(_isrunning)
        {
            //接受数据
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd,inbuff,sizeof(inbuff)-1,0,(struct sockaddr*)&client,&len);
            if(n < 0)
            {
                std::cerr << "recvfrom failed ,errno: "<< errno << " ,err string " << strerror(errno) << std::endl;
                continue;
            }
            inbuff[n] = 0;

            //检查在线用户
            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client,clientip,clientport);

            //将数据发送给所有在线用户
            std::string info = inbuff;
            BroadCast(info,clientip,clientport);
        }
    }

    ~UdpServer()
    {
        if(_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;
    std::string _ip;
    uint16_t _port;
    bool _isrunning;
    std::unordered_map<std::string,struct sockaddr_in> _online_user;
};